package com.nl.controller.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryptUtils {
	
public static void main(String[] args) throws Exception {
	String aesPwd = encrypt("4MQy7**#","7207810001");
	System.out.println("encrypted: " +aesPwd );

}
	
	public static String encrypt(String pwd, String uid) throws Exception {
		try {
			String data = pwd;
			String key = addZeroForNum(uid, 16, 0);
			String iv = addZeroForNum(uid, 16, 1);

			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();
			byte[] dataBytes = data.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength
						+ (blockSize - (plaintextLength % blockSize));
			}
			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
			byte[] encrypted = cipher.doFinal(plaintext);
			return new sun.misc.BASE64Encoder().encode(encrypted);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

/*	public static String decrypt(String pwd, String uid) throws Exception {

		try {
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] pwdBytes = decoder.decodeBuffer(pwd);
			String pwdStr = new String(pwdBytes, "UTF-8");

			String key = addZeroForNum(uid, 16, 0);
			String iv = addZeroForNum(uid, 16, 1);

			byte[] encrypted1 = new BASE64Decoder().decodeBuffer(pwdStr);
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original);
			originalString = originalString.trim();
			return originalString;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}*/

	public static String addZeroForNum(String str, int strLength, int type) {
		int strLen = str.length();
		StringBuffer sb = null;
		while (strLen < strLength) {
			sb = new StringBuffer();
			if (type == 0) {
				sb.append("0").append(str);
			} else if (type == 1) {
				sb.append(str).append("0");
			}
			str = sb.toString();
			strLen = str.length();
		}
		return str;
	}

}

